package com.kiwilss.aopdemo.ui.dsl

import android.text.Editable
import android.text.TextWatcher
import android.widget.EditText

/**
 * @author : Administrator
 * e-mail : kiwilss@163.com
 * time   : 2021/02/05
 * https://juejin.cn/post/6844903760121036807
 *  desc   :  EditText监听扩展
 */

private typealias BeforeTextChangedCallback =
            (s: CharSequence?, start: Int, count: Int, after: Int) -> Unit

private typealias OnTextChangedCallback =
            (s: CharSequence?, start: Int, before: Int, count: Int) -> Unit

private typealias AfterTextChangedCallback =
            (s: Editable?) -> Unit

class TextWatcherBuilder : TextWatcher {
    private var beforeTextChangedCallback: BeforeTextChangedCallback? = null
    private var onTextChangedCallback: OnTextChangedCallback? = null
    private var afterTextChangedCallback: AfterTextChangedCallback? = null

    override fun afterTextChanged(s: Editable?) = afterTextChangedCallback?.invoke(s) ?: Unit

    override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) =
        beforeTextChangedCallback?.invoke(s, start, count, after) ?: Unit

    override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) =
        onTextChangedCallback?.invoke(s, start, before, count) ?: Unit

    fun afterTextChanged(callback: AfterTextChangedCallback) {
        this.afterTextChangedCallback = callback
    }

    fun beforeTextChanged(callback: BeforeTextChangedCallback) {
        this.beforeTextChangedCallback = callback
    }

    fun onTextChanged(callback: OnTextChangedCallback) {
        this.onTextChangedCallback = callback
    }
}

fun textWatcher(function: TextWatcherBuilder.() -> Unit) =
    TextWatcherBuilder().also(function)
